package com.shan.domm.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.shan.domm.common.BaseResponse;
import com.shan.domm.common.ErrorCode;
import com.shan.domm.common.ResultUtils;
import com.shan.domm.common.UserDataListener;
import com.shan.domm.exception.BusinessException;
import com.shan.domm.mapper.UserMapper;
import com.shan.domm.model.domain.DTOs.UserLogin;
import com.shan.domm.model.domain.DTOs.UserRegister;
import com.shan.domm.model.domain.User;
import com.shan.domm.model.excel.UserData;
import com.shan.domm.model.vo.LoginUserVO;
import com.shan.domm.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @PostMapping(value="/regisrer")
    public BaseResponse<Long> userRegister(@RequestBody UserRegister userRegister){

        if(userRegister==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount=userRegister.getUserAccount();
        String userPassword=userRegister.getUserPassword();

        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            return null;
        }
        long result=userService.userRegister(userRegister);

        return ResultUtils.success(result);
    }

    @PostMapping(value = "/login")
    public BaseResponse<User> userLogin(@RequestBody UserLogin userLogin, HttpServletRequest request){
        if(userLogin==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount=userLogin.getUserAccount();
        String userPassword=userLogin.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User userlogin=userService.userLogin(userAccount,userPassword,request);
        return ResultUtils.success(userlogin);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result=userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录态
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @CrossOrigin
    public BaseResponse<User> getLoginUser(HttpServletRequest request){
        User user=userService.getLoginUser(request);
        return ResultUtils.success(user);
    }
    @PostMapping("/addUser")
    public BaseResponse<Long> addUser(@RequestBody User user){
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"提交数据为空");
        }
        long result=userService.addUser(user);
        return ResultUtils.success(result);
    }
    @PostMapping("/deleteUserById")
    public BaseResponse<Long> delete(Integer id){
        if(id==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        long result=userService.deleteUserById(id);
        return ResultUtils.success(result);
    }
    @PostMapping("/updateUser")
    public BaseResponse<Long> updateUser(@RequestBody User user){
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        long result=userService.updateUser(user);
        return ResultUtils.success(result);
    }
    @PostMapping("/searcherUserByName")
    public BaseResponse<List<User>> seacherUser(String name){
        if(name==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        List<User> result=userService.seacherUser(name);
        return ResultUtils.success(result);
    }

    @PostMapping("/pageList")
    public BaseResponse<Page<User>> listPage(Integer current,Integer size){
        if(current==null||size==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Page<User> page=new Page<>(current,size);
        Page<User> pageList=userMapper.selectPage(page,null);
        return ResultUtils.success(pageList);
    }

    @PostMapping("/uploadExcel")
    @ResponseBody
    public BaseResponse<String> upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), UserData.class, new UserDataListener(userService)).sheet().doRead();
        return ResultUtils.success("success");
    }
    @GetMapping("downloadExcel")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = "D:/uploadfile/" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<User> userList=userService.list();
        EasyExcel.write(fileName, User.class).sheet("模板").doWrite(userList);
    }

}
